export default {
	//为当前模块开启命名空间
	namespaced:true,
	state:()=>{
		return {
			cart:JSON.parse(uni.getStorageSync('cart') || '[]')
		}
	},
	mutations:{
		//更改所有商品的勾选状态
		updateAllGoodsState(state,newState){
			state.cart.forEach(item=>item.goods_state = newState);
			this.commit('cart_m/saveToStorage');
		},
		
		//根据goods_id 删除购物车当中的对应商品
		removeGoodsById(state,goods_id){
			//删除数组中的某一项  删除购物车中的商品
			state.cart = state.cart.filter(item=>item.goods_id !== goods_id);
			this.commit('cart_m/saveToStorage');
		},
		
		// 更新购物车当中goods的数量goods_count
		updateGoodsCount(state,goods){
			const findResult = state.cart.find(item=>item.goods_id == goods.goods_id);
			if(findResult){
				findResult.goods_count = goods.goods_count;
				this.commit('cart_m/saveToStorage');
			}
		},
		
		//更新购物车中radio的状态
		updateGoodsState(state,goods){
			//查找state中的cart里的goods_id 和 传递过来的goods_id一致
			const findResult = state.cart.find(item=>item.goods_id == goods.goods_id);
			if(findResult){
				findResult.goods_state = goods.goods_state;
				//存储
				this.commit('cart_m/saveToStorage');
			}
		},
		
		//往state中cart当中增加值   也就是给购物车里添加数据
		addToCart(state,goods){
			//看购物车列表中有没有当前商品goods 有则商品数量+1 goods_count++  没有则用数组方法添加进去 push
			const findResult = state.cart.find(item=>item.goods_id === goods.goods_id);
			if(findResult){
				findResult.goods_count++;
			}else{
				state.cart.push(goods);
			};
			//将最新的cart数据存到storage中
			this.commit("cart_m/saveToStorage")
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart));
		}
	},
	actions:{},
	getters:{
		//勾选商品的总价格
		checkedGoodsAmount(state){
			return state.cart.filter(item=>item.goods_state).reduce((total,item)=>{return total += item.goods_price * item.goods_count},0).toFixed(2)
		},
		
		//全选状态 goods_state
		//所有的选中的商品的数量 同total进行比较  如果相等就是全选
		checkedCount(state){
			// 简写方式
			return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total += item.goods_count,0)
			//分开写
			// 符合条件的过滤出来
			// const resultFilter = state.cart.filter(item=>item.goods_state == true);
			// 符合条件的goods_count 进行累加
			// const sum = resultFilter.reduce((sum,item)=>sum += item.goods_count,0)
			// return sum;
		},
		
		// 商品的总数量
		total(state){
			let sum = 0;
			// state.cart[{goods_count},{}] 遍历求和			
			state.cart.forEach(goods=> sum += goods.goods_count);
			return sum
		}
	}
}